//
//  WYTShopListVC.m
//  WuyouTang
//
//  Created by yunbao02 on 2024/8/28.
//  Copyright © 2024 cat. All rights reserved.
//

#import "WYTShopListVC.h"

#import "NearbyVideoModel.h"
#import "CenterListCell.h"
#import "YBGetVideoObj.h"
#import "ShopCell.h"
#import "OutsideGoodsDetailVC.h"
#import "CommodityDetailVC.h"

@interface WYTShopListVC ()

<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,DZNEmptyDataSetSource,DZNEmptyDataSetDelegate>
{
    BOOL canBackTop;
    NSString *pullurl;
}

@property(nonatomic,assign)int paging;
@property(nonatomic,strong)UIImageView *backimage;
@property(nonatomic,strong)NSMutableArray *videoArray;
@property(nonatomic,strong)NSArray *models;

@end

@implementation WYTShopListVC

-(void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    if (_listType == ListType_Normal) {
        [PublicView hideCenterGif:nil];
    }
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    if ([[Config getOwnID] intValue] <= 0) {
        
    }else{
        [self pullData];

    }
}

-(NSArray *)models{
    NSMutableArray *m_array = [NSMutableArray array];
    for (NSDictionary *dic in self.videoArray) {
        NearbyVideoModel *model = [NearbyVideoModel modelWithDictionary:dic];
        [m_array addObject:model];
    }
    _models = m_array;
    return _models;
}

-(void)pullData {
    
    pullurl = [NSString stringWithFormat:@"User.getShopGoods&touid=%@&p=%d",_otherUid,_paging];
    
    [WYNetworking postWithUrl:pullurl Dic:nil Suc:^(int code, id info, NSString *msg) {
        [_collectionView.mj_footer endRefreshing];
        [_collectionView.mj_header endRefreshing];
        if (code == 0) {
            NSArray *infoA = [NSArray arrayWithArray:info];
            if (_paging==1) {
                [_videoArray removeAllObjects];
            }
            if (infoA.count>0) {
                [_videoArray addObjectsFromArray:infoA];
            }else{
                [_collectionView.mj_footer endRefreshingWithNoMoreData];
            }
            [_collectionView reloadData];
            
        }else{
            [MBProgressHUD showError:msg];
        }
    } Fail:^(id fail) {
        [_collectionView.mj_footer endRefreshing];
        [_collectionView.mj_header endRefreshing];
    }];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.naviView.hidden = YES;
    self.view.backgroundColor = RGB(245, 245, 245);
    _paging = 1;
    self.videoArray = [NSMutableArray array];
    [self.view addSubview:self.collectionView];
    
    canBackTop = NO;
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}
#pragma mark - UICollectionViewDataSource
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    if (kind == UICollectionElementKindSectionFooter){
        UICollectionReusableView *view = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"space_footer" forIndexPath:indexPath];
        view.backgroundColor = UIColor.whiteColor;
        return view;
    }
    return nil;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section;{
    return CGSizeMake(_window_width,ShowDiff);
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return _videoArray.count;
}
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    ShopCell *cell = (ShopCell *)[collectionView dequeueReusableCellWithReuseIdentifier:@"shopCELL" forIndexPath:indexPath];
    NSDictionary *subDic = _videoArray[indexPath.row];
    [cell.thumbImgV sd_setImageWithURL:[NSURL URLWithString:minstr([subDic valueForKey:@"thumb"])]];
    cell.titleL.text = minstr([subDic valueForKey:@"name"]);
    cell.priceL.text = [NSString stringWithFormat:@"¥%@",minstr([subDic valueForKey:@"price"])];
    //type  商品类型   0 站内商品  1 外链商品
    if ([minstr([subDic valueForKey:@"type"]) isEqual:@"1"]) {
        cell.lineLb.hidden = NO;
        cell.sellCountLb.text = [NSString stringWithFormat:@"¥%@",minstr([subDic valueForKey:@"original_price"])];
    }else{
        cell.lineLb.hidden = YES;
        cell.sellCountLb.text =[NSString stringWithFormat:YZMsg(@"已售%@件"),minstr([subDic valueForKey:@"sale_nums"])];
    }
    return cell;
}
#pragma mark - UICollectionViewDelegate
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    NSDictionary *subDic = _videoArray[indexPath.row];
    BOOL isPlatform = [minstr([subDic valueForKey:@"type"]) isEqual:@"2"] ?YES:NO;
    [PublicObj checkGoodsExistenceWithID:minstr([subDic valueForKey:@"id"]) Existence:^(int code, NSString *msg) {
        if (code ==0) {
            if ([minstr([subDic valueForKey:@"type"]) isEqual:@"1"]) {
                OutsideGoodsDetailVC *detail = [[OutsideGoodsDetailVC alloc]init];
                detail.goodsID = minstr([subDic valueForKey:@"id"]);
                detail.liveUid= _otherUid;
                if ([[Config getOwnID] isEqual:_otherUid] && !isPlatform) {
                    detail.fromWhere = @"seller";
                }
                [[YBBaseAppDelegate sharedAppDelegate] pushViewController:detail animated:YES];
            }else{
                CommodityDetailVC *detail = [[CommodityDetailVC alloc]init];
                detail.goodsID = minstr([subDic valueForKey:@"id"]);
                detail.backTags = @"shop";
                detail.liveUid= _otherUid;
                if ([[Config getOwnID] isEqual:_otherUid] && !isPlatform) {
                    detail.fromWhere = @"seller";
                }
                [[YBBaseAppDelegate sharedAppDelegate] pushViewController:detail animated:YES];
            }
        }else{
            [MBProgressHUD showError:msg];
        }
    }];
}
-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
    NSLog(@"lsitvc=====%f===%d",scrollView.contentOffset.y,_collectionView.scrollEnabled);
    if (scrollView.contentOffset.y<=-50) {
        canBackTop = YES;
    }else{
       canBackTop = NO;
    }
}
- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset{
    if (canBackTop == YES) {
        [self.delegate listScrollToTop:velocity.y];
    }
}
#pragma mark - set/get
- (UICollectionView *)collectionView {
    if (!_collectionView) {
        UICollectionViewFlowLayout *flow = [[UICollectionViewFlowLayout alloc]init];
        flow.scrollDirection = UICollectionViewScrollDirectionVertical;
        // flow.itemSize = CGSizeMake(_window_width/3-1, _window_width/3*4/3);
        flow.itemSize = CGSizeMake((_window_width-21)/2, (_window_width-21)/2 + 75);
        flow.minimumLineSpacing = 1;
        flow.minimumInteritemSpacing = 0.5;
        CGFloat HH = _window_height-44-64-49-statusbarHeight;
        if (!_isTabbar) {
            HH = _window_height-44-64-statusbarHeight;
        }
        _collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0,0, _window_width, HH) collectionViewLayout:flow];
        [self.collectionView registerNib:[UINib nibWithNibName:@"shopCell" bundle:nil] forCellWithReuseIdentifier:@"shopCELL"];
        _collectionView.showsVerticalScrollIndicator = NO;
        _collectionView.delegate =self;
        _collectionView.dataSource = self;
        _collectionView.backgroundColor = UIColor.whiteColor;
        _collectionView.scrollEnabled = NO;
        [_collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"space_footer"];
        _collectionView.emptyDataSetSource = self;
        _collectionView.emptyDataSetDelegate = self;
        _collectionView.mj_insetB = -ShowDiff;
        YBWeakSelf;
        _collectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            weakSelf.paging = 1;
            [self pullData];
        }];
        self.collectionView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
            weakSelf.paging +=1;
            [self pullData];
        }];
    }
    return _collectionView;
}

- (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView {
    NSString *text = @"";
    if (![_otherUid isEqual:[Config getOwnID]]) {
        text = @"TA还没有发布过商品";
    }else {
        text = YZMsg(@"你发布的商品都会放到这里");
    }
    NSDictionary *attributes = @{NSFontAttributeName: ybNodataFont,
                                 NSForegroundColorAttributeName: ybNodataCol};
    return [[NSAttributedString alloc] initWithString:text attributes:attributes];
}

- (CGFloat)verticalOffsetForEmptyDataSet:(UIScrollView *)scrollView{
    CGFloat moveY = -(statusbarHeight+64+44);
    return moveY;
}
- (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView{
    return NO;
}

@end
